package com.shopping.service.record;

import com.shopping.constant.ResponseCode;
import com.shopping.dao.RecordDao;
import com.shopping.pojo.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    RecordDao recordDao;

    @Override
    public Map<String, Object> addRecord(Record record) {
        Map<String, Object> map = new HashMap<>();
        try {
            Record selectRecord = recordDao.select(record.getUserId(), record.getTradeId());
            if(selectRecord != null){
                recordDao.updateTime(record.getTime(), record.getUserId(), record.getTradeId());
            }else{
                recordDao.insert(record);
            }
            map.put("code", ResponseCode.REQUEST_SUCCESSED.getValue());
        }catch (Exception e){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public Map<String, Object> deleteRecord(int id) {
        Map<String, Object> map = new HashMap<>();
        try {
            Record record = recordDao.selectRecord(id);
            if(record == null){
                map.put("code", ResponseCode.ENTITY_NOT_EXISTS.getValue());
                return map;
            }
            recordDao.delete(id);
            List<Record> records = recordDao.selectRecords(record.getUserId());
            map.put("code", ResponseCode.REQUEST_SUCCESSED.getValue());
            map.put("records", records);
        }catch (Exception e){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public Map<String, Object> deleteAllRecords(int userId) {
        Map<String, Object> map = new HashMap<>();
        try {
            recordDao.deleteAll(userId);
            map.put("code", ResponseCode.REQUEST_SUCCESSED.getValue());
        }catch (Exception e){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public Map<String, Object> showRecords(int userId) {
        Map<String, Object> map = new HashMap<>();
        try {
            List<Record> records = recordDao.selectRecords(userId);
            if(records.size() == 0){
                map.put("code", ResponseCode.ENTITY_NOT_EXISTS.getValue());
                return map;
            }
            map.put("code", ResponseCode.REQUEST_SUCCESSED.getValue());
            map.put("records", records);
        }catch (Exception e){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            e.printStackTrace();
        }
        return map;
    }

}
